VFG.Model=function(){
}
VFG.Model.Layers= new Cesium.PrimitiveCollection();
VFG.Model.Primitives=new Map();

VFG.Model.addModel=function(viewer,ops,localModelUrl,isLocal){
	if('GLTF'==ops.type){
		this.createGltfPrimitive(viewer,ops,localModelUrl,isLocal);
	}
	else if('3DTILES'==ops.type){
		this.create3DTilePrimitive(viewer,ops,localModelUrl,isLocal);
	}
}

VFG.Model.createGltfPrimitive=function(viewer,ops,localModelUrl,isLocal){
	var _this=this;
	if(!ops){
		console.log('参数必填!!!');
		return;
	}
	
	if(!ops.url){
		console.log('模型地址必填!!!');
		return;
	}
	
	if('GLTF'!=ops.type){
		console.log('模型格式必需是GLTF!!!');
		return;
	}
	if(!(ops.x && ops.y)){
		console.log('坐标必填!!!');
		return;
	}
/*	viewer.scene.light = new Cesium.DirectionalLight({ //去除时间原因影响模型颜色
         direction: new Cesium.Cartesian3(0.35492591601301104, -0.8909182691839401, -0.2833588392420772)
       })*/
	if(!this.Primitives.has(ops.id)){
		var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(ops.displayNear,ops.displayFar);
		var model = this.Layers.add(Cesium.Model.fromGltf({
			id:ops.id,
			name:ops.name||'未命名',
			url: ops.url,
			type:ops.type,
			bizType:ops.code||'',
			show : ( ops.show &&  ops.show!='1')?false : true,                     
			modelMatrix : this.getModelMatrix(ops),
			scale: ops.scale*1||1,
			minimumPixelSize:(ops.minimumPixelSize)?ops.minimumPixelSize*1:0,
			maximumScale:(ops.minimumPixelSize)?ops.minimumPixelSize*1:undefined,
			allowPicking : true,        
			debugShowBoundingVolume : false, 
			debugWireframe : false,
			distanceDisplayCondition:distanceDisplayCondition?distanceDisplayCondition:undefined,
			backFaceCulling:false,
			//colorBlendMode:(ops.oftenShow=="1")?this.getColorBlendMode(ops.colorBlendMode):null,  //设置颜色与原纹理的混合关系
			//silhouetteColor:(ops.oftenShow=="1")? (ops.silhouetteColor? Cesium.Color.fromCssColorString(ops.silhouetteColor):Cesium.Color.BLACK):null,		
			//silhouetteSize:(ops.oftenShow=="1")? ops.silhouetteSize*1:null,		
			//color:(ops.oftenShow=="1")?  (ops.color? Cesium.Color.fromCssColorString(ops.color):Cesium.Color.fromCssColorString("rgba(255,255,255,1)")):Cesium.Color.fromCssColorString("rgba(255,255,255,1)"),			
		}));
		
		
		
		
		model.readyPromise.then(function(model) {
	       model.activeAnimations.addAll({
	         loop:_this.getLoop(ops.loop),//控制重复
	         speedup:ops.loop?ops.loop*1: 0.5, // 速度，相对于clock
	         reverse: ops.reverse?ops.reverse*1:false // 动画反转
	       })
		}).otherwise(function(error){
	    });
		this.Primitives.set(ops.id,model);
		return model;
	}else{
		return this.Primitives.get(ops.id);
	}
}

VFG.Model.create3DTilePrimitive=function(viewer,ops,localModelUrl,isLocal){
	var _this=this;
	if(!ops){
		console.log('参数必填!!!');
		return;
	}
	
	if(!ops.url){
		console.log('模型地址必填!!!');
		return;
	}
	
	if('3DTILES'!=ops.type){
		console.log('模型格式必需是3DTILES!!!');
		return;
	}
	
	if(!this.Primitives.has(ops.id)){
		var url=ops.url;
		if(isLocal==true){
			var protocol = window.location.protocol;
			if('https:'==protocol){
				url=url.replace(localModelUrl, "https://localhost:888")
			}else{
				url=url.replace(localModelUrl, "http://localhost")
			}
		}
		var primitive=this.Layers.add(new Cesium.Cesium3DTileset({
			id : ops.id,
			url : url,
			name : ops.name ||'未命名',
			show : ( ops.show &&  ops.show!='1')?false : true,    
			bizType:ops.code||'',
			preferLeaves:(ops && ops.preferLeaves && ops.preferLeaves=='1')?true:false,
			imageBasedLightingFactor :Cesium.Cartesian2(1.0, 1.0),
			loadSiblings:true,
			skipLevels:ops.skipLevels ? ops.skipLevels*1: 1,
			baseScreenSpaceError:ops.baseScreenSpaceError ? ops.baseScreenSpaceError*1: 1024,
			skipScreenSpaceErrorFactor:ops.skipScreenSpaceErrorFactor ? ops.skipScreenSpaceErrorFactor*1: 16,
			maximumMemoryUsage:ops.maximumMemoryUsage ? ops.maximumMemoryUsage*1: 512,
			maximumScreenSpaceError : ops.maximumScreenSpaceError ? ops.maximumScreenSpaceError*1: 16,
			skipLevelOfDetail : ops.skipLevelOfDetail ? (ops.skipLevelOfDetail=='on'?true:false): false,
			maximumNumberOfLoadedTiles : ops.maximumNumberOfLoadedTiles ? ops.maximumNumberOfLoadedTiles*1: 1024, //最大加载瓦片个数			
		}));
		
		primitive.readyPromise.then(function(tileset) {
			if(ops.x && ops.y ){
	                tileset._root.transform=_this.get3dtilesMaxtrix(ops);
	               // tileset._root.transform =_this.get3dtilesMaxtrix(ops);
			}else{
	            var heightOffset =ops.z || 0;  //高度
	            var boundingSphere = tileset.boundingSphere; 
	            var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
	            var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
	            var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
	            var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
	            tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
			}
			
		    if(ops.callBack){
		    	var param=VFG.Util.getCenterForModel(tileset,tileset._root.transform);
		    	ops.callBack({
		    		state:true,
		    		message:'成功',
		    		param:param
		    	});
		    }
		    
		}).otherwise(function(error){
		    if(ops.callBack){
		    	ops.callBack({
		    		state:false,
		    		message:error
		    	});
		    }
	    });
		
		primitive.allTilesLoaded.addEventListener(function() {
            console.log('All tiles are loaded');
        });
		
		this.Primitives.set(ops.id,primitive);
		return primitive;
	}else{
		return this.Primitives.get(ops.id);
	}
}

/**
 * id查询点
 */
VFG.Model.getById=function(id){
	if(this.Primitives.has(id)){
		return this.Primitives.get(id);
	}
}


/**
 * 显示隐藏
 */
VFG.Model.showOrHideById=function(id,state){
	if(this.Primitives.has(id)){
		this.Primitives.get(id).show=state;
	}
}

VFG.Model.show=function(option){
	if(this.Primitives.has(option.id)){
		this.Primitives.get(option.id).show=option.show;
	}
} 

VFG.Model.removeById=function(id){ 
	if(this.Primitives.has(id)){
		if(this.Layers.remove(this.Primitives.get(id))){
			this.Primitives.delete(id);
		}
	}
}

VFG.Model.getModelMatrix=function(ops){
	var heading = Cesium.defaultValue(ops.ry, 0.0);
    var pitch = Cesium.defaultValue(ops.rx, 0.0);
    var roll = Cesium.defaultValue(ops.rz, 0.0);
    var headingPitchRoll = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(heading), Cesium.Math.toRadians(pitch), Cesium.Math.toRadians(roll));
    var origin = Cesium.Cartesian3.fromDegrees(ops.x*1, ops.y*1,ops.z*1);
	return Cesium.Transforms.headingPitchRollToFixedFrame(origin, headingPitchRoll, Cesium.Ellipsoid.WGS84, Cesium.Transforms.eastNorthUpToFixedFrame, new Cesium.Matrix4());
}
VFG.Model.get3dtilesMaxtrix=function(ops){
	 var rx = Cesium.defaultValue(ops.rx, 0.0);
    var ry = Cesium.defaultValue(ops.ry, 0.0);
    var rz = Cesium.defaultValue(ops.rz, 0.0);
    var transformPosition =Cesium.Cartesian3.fromDegrees(ops.x*1, ops.y*1,ops.z*1);
    var matrix = Cesium.Transforms.eastNorthUpToFixedFrame(transformPosition);
    var scale = Cesium.Matrix4.fromUniformScale(ops.scale*1);
    Cesium.Matrix4.multiply(matrix, scale, matrix);
    
    var rotationX = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(rx));
    var rotationY = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(ry));
    var rotationZ = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(rz));
    
    
    var rotationTranslationX = Cesium.Matrix4.fromRotationTranslation(rotationX);
    var rotationTranslationY = Cesium.Matrix4.fromRotationTranslation(rotationY);
    var rotationTranslationZ = Cesium.Matrix4.fromRotationTranslation(rotationZ);
    
    Cesium.Matrix4.multiply(matrix, rotationTranslationX, matrix);
    Cesium.Matrix4.multiply(matrix, rotationTranslationY, matrix);
    Cesium.Matrix4.multiply(matrix, rotationTranslationZ, matrix);
    return matrix;
}



VFG.Model.update = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		this.Primitives.get(ops.id).modelMatrix=_this.getModelMatrix(ops);
	}
};

VFG.Model.updateScale = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		this.Primitives.get(ops.id).scale=ops.scale*1;
	}
};

VFG.Model.getColorBlendMode = function(value) {
	var _this = this;
	if("0"==value){
		return Cesium.ColorBlendMode.HIGHLIGHT;//材质与设置颜色相乘得到的颜色。
	}
	else if("1"==value){
		return Cesium.ColorBlendMode.MIX;//材质与设置颜色混合得到的颜色，是怎么混合的，还需要研究源码。
	}
	else if("2"==value){
		return Cesium.ColorBlendMode.REPLACE;//设置颜色替换材质。
	}
};

VFG.Model.getLoop = function(value) {
	var _this = this;
	if("0"==value){
		return Cesium.ModelAnimationLoop.MIRRORED_REPEAT;
	}
	else if("1"==value){
		return Cesium.ModelAnimationLoop.NONE;
	}
	else if("2"==value){
		return Cesium.ModelAnimationLoop.REPEAT;
	}else{
		return Cesium.ModelAnimationLoop.MIRRORED_REPEAT;
	}
};

VFG.Model.updateHighlight = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		var Primitive=this.Primitives.get(ops.id);
		if(ops.oftenShow=="1"){
			if(ops.color) Primitive.color =Cesium.Color.fromCssColorString(ops.color)
			if(ops.colorBlendMode) Primitive.colorBlendMode=this.getColorBlendMode(ops.colorBlendMode);
			if(ops.silhouetteColor) Primitive.silhouetteColor= Cesium.Color.fromCssColorString(ops.silhouetteColor);
			if(ops.silhouetteSize) Primitive.silhouetteSize=ops.silhouetteSize*1;
		}else{
			Primitive.color =Cesium.Color.fromCssColorString("rgba(255,255,255,1)");//设置模型颜色与透明度
			Primitive.colorBlendMode=Cesium.ColorBlendMode.HIGHLIGHT;
			Primitive.silhouetteColor=null;
			Primitive.silhouetteSize=null;
		}
	}
};

VFG.Model.select = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		var Primitive=this.Primitives.get(ops.id);
		if(ops.oftenShow=="1"){
			if(ops.color) Primitive.color =Cesium.Color.fromCssColorString(ops.color)
			if(ops.colorBlendMode) Primitive.colorBlendMode=this.getColorBlendMode(ops.colorBlendMode);
			if(ops.silhouetteColor) Primitive.silhouetteColor= Cesium.Color.fromCssColorString(ops.silhouetteColor);
			if(ops.silhouetteSize) Primitive.silhouetteSize=ops.silhouetteSize*1;
		}
	}
};

VFG.Model.unselect = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		var Primitive=this.Primitives.get(ops.id);
		if(ops.oftenShow=="1"){
			Primitive.color =Cesium.Color.fromCssColorString("rgba(255,255,255,1)");//设置模型颜色与透明度
			Primitive.colorBlendMode=Cesium.ColorBlendMode.HIGHLIGHT;
			Primitive.silhouetteColor=null;
			Primitive.silhouetteSize=null;
		}
	}
};





